<template>
  <div class="stock-filter-bar">
    <div class="filter-section config-section">
      <!-- 票据类型筛选 -->
      <div class="filter-section">
        <span class="filter-label">票据类型</span>
        <div class="tag-container">
          <span
            v-for="tag in ticketTypeTags"
            :key="tag.value"
            class="text-tag"
            :class="{ active: tag.type === 'primary' }"
            @click="handleTypeTagClick(tag)"
          >
            <span class="text-tag-label">{{ tag.label }}</span>
          </span>
        </div>

        <!-- 提交按钮 -->
        <el-button type="primary" size="small" class="submit-button" @click="handleTypeSubmit">提交</el-button>
      </div>
    </div>

    <div class="filter-section config-section">
      <!-- 金额范围配置 -->
      <div class="filter-section">
        <span class="filter-label">金额范围</span>
        <div class="tag-container">
          <span
            v-for="tag in amountTags"
            :key="tag.value"
            class="text-tag"
            :class="{ active: tag.type === 'primary' }"
            @click="handleAmountTagClick(tag)"
          >
            <span class="text-tag-label">{{ tag.label }}</span>
            <span class="text-tag-close" @click.stop="handleAmountClose(tag)">×</span>
          </span>
        </div>
      </div>
    </div>

    <div class="filter-section config-section">
      <!-- 到期日期设置 -->
      <div class="filter-section">
        <span class="filter-label">到期日期</span>
        <div class="tag-container">
          <span
            v-for="tag in dueDateTags"
            :key="tag.value"
            class="text-tag"
            :class="{ active: tag.type === 'primary' }"
            @click="handleDueDateTagClick(tag)"
          >
            <span class="text-tag-label">{{ tag.label }}</span>
            <span class="text-tag-close" @click.stop="handleDueDateClose(tag)">×</span>
          </span>
        </div>
      </div>
    </div>

    <div class="filter-section rate-config-section">
      <!-- 利率配置 -->
      <div class="filter-section">
        <span class="filter-label">利率配置</span>
        <div class="tag-container rate-container">
          <div class="input-row">
            <div class="input-group">
              <label class="input-label">利率(%)</label>
              <el-input-number
                class="rate-input"
                v-model="ratePercent"
                :min="0"
                :max="100"
                :step="0.01"
                :precision="2"
                size="large"
                controls-position="right"
                placeholder="请输入利率(%)"
              />
            </div>
            <div class="operator-symbol">+</div>
            <div class="input-group">
              <label class="input-label">固定金额(元)</label>
              <el-input-number
                class="rate-input"
                v-model="fixedAmount"
                :min="0"
                :max="100000000"
                :step="1"
                :precision="0"
                size="large"
                controls-position="right"
                placeholder="请输入固定金额(元)"
              />
            </div>
          </div>

          <el-button size="large" type="success" class="rate-submit-btn" @click="onRateSubmit">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue"
import { ElMessage } from "element-plus"
import {
  getBankTypeDictAllListApi,
  getAmountRangesByIdsApi,
  getRateDateRangesAllListApi,
  deleteRateDateRangeApi,
  getRatesReadApi,
  updateRateApi
} from "../../../../../api/calculator/index"
import type { TagItem, BankTypeItem, AmountRangeItem, RateItem } from "./types"

// 数据状态
const ticketTypeTags = ref<TagItem[]>([])
const amountTags = ref<TagItem[]>([])
const dueDateTags = ref<TagItem[]>([])

// 利率配置
const rateTouched = ref<boolean>(false)
const ratePercent = ref<number | undefined>(undefined) // 利率百分比
const fixedAmount = ref<number | undefined>(undefined) // 固定金额
const currentRateId = ref<number | undefined>(undefined) // 存储当前利率记录的ID

// 计算属性：获取当前选中的ID（多选模式下取第一个选中的）
const selectedTypeId = computed(() => {
  const selectedTypes = ticketTypeTags.value.filter((t) => t.type === "primary")
  return selectedTypes.length > 0 ? Number(selectedTypes[0].value) : undefined
})

// 计算属性：获取所有选中的类型ID数组
const selectedTypeIds = computed(() => {
  return ticketTypeTags.value.filter((t) => t.type === "primary").map((t) => Number(t.value))
})

const selectedRangeId = computed(() => {
  const selectedRange = amountTags.value.find((t) => t.type === "primary")
  return selectedRange ? Number(selectedRange.value) : undefined
})

const selectedDateRangeId = computed(() => {
  const selectedDate = dueDateTags.value.find((t) => t.type === "primary")
  return selectedDate ? Number(selectedDate.value) : undefined
})

// ==================== 票据类型相关 ====================
// 处理票据类型标签点击
const handleTypeTagClick = async (tag: TagItem) => {
  // 多选模式：切换当前标签的选中状态
  if (tag.type === "primary") {
    tag.type = ""
  } else {
    tag.type = "primary"
  }

  // 只记录选中状态，不触发联动
  console.log("选中票据类型:", tag)
  console.log(
    "当前所有选中的类型:",
    ticketTypeTags.value.filter((t) => t.type === "primary")
  )
}

// 处理提交按钮点击
const handleTypeSubmit = () => {
  // 获取当前选中的类型
  const selectedTypes = ticketTypeTags.value.filter((t) => t.type === "primary")

  if (selectedTypes.length === 0) {
    ElMessage.warning("请至少选择一种票据类型")
    return
  }

  // 触发变化事件和联动
  handleTypeChange(selectedTypes)
  handleTypeSelect(selectedTypes[0]) // 触发选中事件，联动金额范围
  ElMessage.success("票据类型选择已提交")
}

// 获取银行类型数据
const loadBankTypes = async () => {
  try {
    const response = await getBankTypeDictAllListApi({})
    if (response.code === 200 && response.data?.data) {
      const bankTypes = response.data.data as BankTypeItem[]
      ticketTypeTags.value = bankTypes.map((item) => ({
        label: item.type_name,
        value: item.type_id.toString(),
        type: "" // 初始状态都不选中，支持多选
      }))
    }
  } catch (error) {
    console.error("获取银行类型失败:", error)
    ElMessage.error("获取银行类型失败")
  }
}

// 事件处理函数 - 当点击提交按钮时触发
const handleTypeChange = (selectedTypes: TagItem[]) => {
  console.log("票据类型提交:", selectedTypes)
  console.log("选中的类型ID数组:", selectedTypeIds.value)
  // 重置利率配置
  initializeRateConfig()
}

const handleTypeSelect = (tag: TagItem) => {
  console.log("选中票据类型:", tag)
  console.log(
    "当前所有选中的类型:",
    ticketTypeTags.value.filter((t) => t.type === "primary")
  )
  // 重置利率配置
  initializeRateConfig()
}

// ==================== 金额范围相关 ====================
// 监听选中的票据类型变化
watch(
  () => selectedTypeId.value,
  async (newTypeId) => {
    if (newTypeId) {
      await loadAmountRanges(newTypeId)
    } else {
      amountTags.value = []
    }
  },
  { immediate: true }
)

/**
 * 处理票面金额标签点击（单选）
 * 点击后清空其他选中，仅保留当前，并刷新到期日期标签
 */
const handleAmountTagClick = async (tag: TagItem) => {
  // 单选：清空所有，再选中当前
  amountTags.value.forEach((t) => (t.type = ""))
  tag.type = "primary"

  handleRangeSelect(tag)

  const selectedRanges = amountTags.value.filter((t) => t.type === "primary")
  handleAmountChange(selectedRanges)
}

/**
 * 删除票面金额标签
 * 只删除本地数组中的数据，不调用后台API
 */
const handleAmountClose = (tag: TagItem) => {
  const index = amountTags.value.indexOf(tag)
  if (index > -1) {
    amountTags.value.splice(index, 1)

    const selectedRanges = amountTags.value.filter((t) => t.type === "primary")
    handleAmountChange(selectedRanges)
  }
}

// 加载金额范围数据
const loadAmountRanges = async (bankTypeId?: number) => {
  amountTags.value = []
  try {
    // 使用getAmountRangesByIdsApi需要传递ID数组
    // 这里需要根据bankTypeId获取对应的金额范围ID数组
    const data: any = {}
    if (bankTypeId) {
      // 假设需要传递type_id来获取对应的金额范围ID数组
      data.ids = bankTypeId
    }

    const response = await getAmountRangesByIdsApi(data)
    console.log("金额范围API响应:", response)

    if (response.code === 200 && response.data?.data && response.data.data.length > 0) {
      const amountRanges = response.data.data as AmountRangeItem[]

      // 将API返回的金额范围数据转换为标签格式
      amountTags.value = amountRanges.map((item, index) => ({
        label: item.name, // 使用API返回的name字段作为显示标签
        value: item.range_id.toString(), // 使用range_id作为值
        type: index === 0 ? "primary" : "" // 默认选中第一个
      }))

      console.log("转换后的金额标签:", amountTags.value)

      // 触发选中事件
      const selectedRanges = amountTags.value.filter((t) => t.type === "primary")
      if (selectedRanges.length > 0) {
        handleAmountChange(selectedRanges)
        handleRangeSelect(selectedRanges[0])
      }
    } else {
      // 如果API没有返回数据，清空金额标签
      amountTags.value = []
      if (bankTypeId) {
        ElMessage.error("请先设置金额区间")
      }
      console.log("API未返回金额范围数据，金额标签已清空")
    }
  } catch (error) {
    console.error("加载金额范围失败:", error)
    ElMessage.error("加载金额范围失败")

    // 出错时清空金额标签
    amountTags.value = []
  }
}

const handleAmountChange = (selectedRanges: TagItem[]) => {
  console.log("金额范围变化:", selectedRanges)
  // 重置利率配置
  initializeRateConfig()
}

const handleRangeSelect = (tag: TagItem) => {
  console.log("选中金额范围:", tag)
  // 重置利率配置
  initializeRateConfig()
}

// ==================== 到期日期相关 ====================
// 监听选中的金额区间变化
watch(
  () => selectedRangeId.value,
  async (newRangeId) => {
    if (newRangeId) {
      await loadDueDateTags(newRangeId)
    } else {
      dueDateTags.value = []
    }
  },
  { immediate: true }
)

/**
 * 处理到期日期标签点击（单选）
 * 点击后清空其他选中，仅保留当前，并联动利率
 */
const handleDueDateTagClick = async (tag: TagItem) => {
  // 单选：清空所有，再选中当前
  dueDateTags.value.forEach((t) => (t.type = ""))
  tag.type = "primary"

  handleDateSelect(tag)

  const selectedDates = dueDateTags.value.filter((t) => t.type === "primary")
  handleDateChange(selectedDates)
}

/**
 * 删除到期日期标签：调用后端接口删除，并刷新列表与利率
 */
const handleDueDateClose = async (tag: TagItem) => {
  // 解析 date_range_id
  const dateRangeId = Number(tag.value)
  if (!Number.isFinite(dateRangeId)) {
    ElMessage.error("无效的到期日期标识")
    return
  }
  try {
    const res = await deleteRateDateRangeApi({ date_range_id: dateRangeId })
    if (res.code === 200) {
      ElMessage.success("删除到期日期范围成功")
      // 刷新到期日期列表（根据当前金额或类型上下文）
      if (selectedRangeId.value) {
        await loadDueDateTags(selectedRangeId.value)
      }
    } else {
      ElMessage.error(res.message || "删除到期日期范围失败")
    }
  } catch (e) {
    console.error("删除到期日期范围失败:", e)
    ElMessage.error("删除到期日期范围失败")
  }
}

const loadDueDateTags = async (rangeId?: number) => {
  try {
    const params: any = {}
    if (rangeId) params.range_id = rangeId
    const res = await getRateDateRangesAllListApi(params)
    if (res.code === 200 && res.data) {
      const list = res.data as any[] as RateItem[]
      dueDateTags.value = list.map((item, index) => {
        const label = `${item.start_date} - ${item.end_date}`
        const value = String(item.date_range_id ?? `${item.start_date}-${item.end_date}`)
        return {
          label,
          value,
          type: index === 0 ? "primary" : ""
        }
      })

      // 触发选中事件
      const selectedDates = dueDateTags.value.filter((t) => t.type === "primary")
      if (selectedDates.length > 0) {
        handleDateChange(selectedDates)
        handleDateSelect(selectedDates[0])
      }
    } else {
      dueDateTags.value = []
    }
  } catch (e) {
    console.error("加载到期日期失败:", e)
    ElMessage.error("加载到期日期失败")
    dueDateTags.value = []
  }
}

const handleDateChange = (selectedDates: TagItem[]) => {
  console.log("到期日期变化:", selectedDates)
}

const handleDateSelect = (tag: TagItem) => {
  console.log("选中到期日期:", tag)
}

// ==================== 利率配置相关 ====================
// 初始化利率配置
const initializeRateConfig = () => {
  ratePercent.value = undefined
  fixedAmount.value = undefined
  rateTouched.value = false
  currentRateId.value = undefined
}

// 监听选中的日期区间变化
watch(
  () => selectedDateRangeId.value,
  async (newDateRangeId) => {
    if (newDateRangeId) {
      await loadRateBySelection()
    } else {
      initializeRateConfig()
    }
  },
  { immediate: true }
)

// 根据当前选中的金额区间与日期区间，从后台读取利率
const loadRateBySelection = async () => {
  console.log("loadRateBySelection")
  const dateRangeId = selectedDateRangeId.value
  if (!dateRangeId || !Number.isFinite(dateRangeId)) return

  try {
    const res = await getRatesReadApi({ date_range_id: dateRangeId })
    console.log("读取利率结果:", res)
    if (res.code === 200 && res.data) {
      // 存储利率记录ID
      currentRateId.value = res.data.rate_id
      console.log("读取到的利率记录ID:", currentRateId.value)

      // 读取利率百分比
      const serverRatePercent = res.data.rate_percent != null ? Number(res.data.rate_percent) : undefined
      if (Number.isFinite(serverRatePercent)) {
        ratePercent.value = serverRatePercent
      }

      // 读取固定金额
      const serverFixedAmount = res.data.fixed_amount != null ? Number(res.data.fixed_amount) : undefined
      if (Number.isFinite(serverFixedAmount)) {
        fixedAmount.value = serverFixedAmount
      }

      console.log("读取到的利率百分比:", ratePercent.value)
      console.log("读取到的固定金额:", fixedAmount.value)
    } else {
      // 无记录：清空数据
      currentRateId.value = undefined
    }
  } catch (e) {
    console.error("读取利率失败:", e)
  }
}

// 处理利率提交
const onRateSubmit = async () => {
  const rangeId = selectedRangeId.value
  const dateRangeId = selectedDateRangeId.value

  if (!rangeId || !Number.isFinite(rangeId)) {
    ElMessage.error("请先选择金额区间")
    return
  }
  if (!dateRangeId || !Number.isFinite(dateRangeId)) {
    ElMessage.error("请先选择到期日期")
    return
  }

  // 检查是否至少有一个值被输入
  if (
    (ratePercent.value == null || isNaN(Number(ratePercent.value))) &&
    (fixedAmount.value == null || isNaN(Number(fixedAmount.value)))
  ) {
    ElMessage.error("请至少输入利率或固定金额中的一个")
    return
  }

  try {
    const updateData: any = {
      range_id: rangeId,
      date_range_id: dateRangeId
    }

    // 添加利率百分比
    if (ratePercent.value != null && !isNaN(Number(ratePercent.value))) {
      updateData.rate_percent = ratePercent.value
    }

    // 添加固定金额
    if (fixedAmount.value != null && !isNaN(Number(fixedAmount.value))) {
      updateData.fixed_amount = fixedAmount.value
    }

    // 如果有现有记录ID，添加到请求中
    if (currentRateId.value) {
      updateData.rate_id = currentRateId.value
    }

    const upd = await updateRateApi(updateData)
    if (upd.code === 200) {
      ElMessage.success("利率配置已更新")
    } else {
      ElMessage.error(upd.message || "更新利率配置失败")
      return
    }

    // 提交后标记触摸
    rateTouched.value = true
  } catch (e) {
    console.error("提交失败:", e)
    ElMessage.error("提交失败")
  }

  handleRateSubmit(ratePercent.value, fixedAmount.value)
}

const handleRateSubmit = (ratePercent: number | undefined, fixedAmount: number | undefined) => {
  console.log("利率提交:", { ratePercent, fixedAmount })
}

// 初始化加载
onMounted(async () => {
  // 加载银行类型数据
  await loadBankTypes()
})

// 暴露方法给父组件
defineExpose({
  // 获取选中的数据
  getSelectedType: () => ticketTypeTags.value.find((t) => t.type === "primary"),
  getSelectedTypes: () => ticketTypeTags.value.filter((t) => t.type === "primary"), // 新增：获取所有选中的类型
  getSelectedTypeIds: () => selectedTypeIds.value, // 新增：获取所有选中的类型ID数组
  getSelectedRange: () => amountTags.value.find((t) => t.type === "primary"),
  getSelectedDate: () => dueDateTags.value.find((t) => t.type === "primary"),

  // 重置所有配置
  resetAll: () => {
    ticketTypeTags.value = []
    amountTags.value = []
    dueDateTags.value = []
    initializeRateConfig()
  },

  // 加载数据方法
  loadBankTypes,
  loadAmountRanges,
  loadDueDateTags,
  loadRateBySelection
})
</script>

<style scoped lang="scss">
.stock-filter-bar {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
  border-radius: 8px;
  display: flex;
  flex-direction: row;
  gap: 16px;
  align-items: flex-start;

  .filter-section {
    flex: 1;
    min-width: 0;
    margin-bottom: 0;
    padding: 0;
    border-bottom: none;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 10px;
    height: 100%;
  }

  .config-section {
    background-color: #f9fafc;
    padding: 16px;
    border-radius: 8px;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    min-height: 400px;
  }

  .rate-config-section {
    background-color: #f9fafc;
    padding: 16px;
    border-radius: 8px;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    min-height: 400px;
  }

  .filter-label {
    font-weight: 500;
    color: #333;
    margin-bottom: 12px;
    margin-right: 0;
    min-width: auto;
    font-size: 14px;
    width: 100%;
    text-align: center;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
  }

  .tag-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    margin-right: 0;
    width: 100%;
  }

  /* 文本标签样式 */
  .text-tag {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
    color: #666;
    border: 1px solid transparent;
    user-select: none;
  }
  .text-tag:hover {
    color: #409eff;
  }
  .text-tag.active {
    color: #409eff;
    font-weight: 500;
    border-color: rgba(64, 158, 255, 0.2);
    background-color: rgba(64, 158, 255, 0.05);
  }
  .text-tag-label {
    line-height: 1;
  }
  .text-tag-close {
    margin-left: 4px;
    font-size: 14px;
    color: #999;
    cursor: pointer;
    &:hover {
      color: #f56c6c;
    }
  }

  /* 提交按钮样式 */
  .submit-button {
    margin-top: 15px;
    align-self: center;
    width: 80%;
  }

  /* 利率配置样式 */
  .rate-container {
    .input-row {
      display: flex;
      align-items: center;
      gap: 10px;
      width: 100%;
    }

    .input-group {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    .input-label {
      font-size: 14px;
      color: #606266;
    }

    .operator-symbol {
      font-size: 18px;
      font-weight: bold;
      color: #606266;
      margin: 0 5px;
      margin-top: 20px;
    }
  }

  :deep(.el-tag) {
    margin-right: 8px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.3s;
    border-radius: 4px;

    &.el-tag--primary {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
      font-weight: 500;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }
  }

  :deep(.el-input-number) {
    width: 100%;

    .el-input__wrapper {
      box-shadow: 0 0 0 1px #dcdfe6 inset;

      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }

      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  // 专门针对利率配置区域的样式
  .rate-config-section {
    :deep(.rate-input.el-input-number) {
      width: 100%;
      margin-bottom: 8px;
    }

    :deep(.el-input-number .el-input__wrapper) {
      width: 100%;
    }

    :deep(.rate-submit-btn) {
      width: 100%;
      margin-top: 12px;
    }
  }

  :deep(.el-button) {
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    &.el-button--primary {
      background-color: #409eff;

      &:hover {
        background-color: #66b1ff;
      }
    }
  }

  :deep(.section-title) {
    font-size: 14px;
    font-weight: 600;
    color: #606266;
    margin-bottom: 12px;
    display: flex;
    align-items: center;

    &::before {
      content: "";
      display: inline-block;
      width: 4px;
      height: 14px;
      background-color: #409eff;
      margin-right: 8px;
      border-radius: 2px;
    }
  }
}
</style>
